package yicheng.dinnertogetherapp;

import java.util.HashMap;

import yicheng.dinnertogetherapp.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FriendInfoActivity extends Activity{
	TextView friendNickname_textView, friendPhoneNumber_textView, friendAvailability_textView, friendPreference_textView;
	RelativeLayout friendInfo_loading_layout;
	RelativeLayout friendInfo_layout;
	Button text_button, call_button;
	CheckBox invisibleToThisFriend_checkBox;
	
	AmazonClientManager clientManager;
	
	String FRIEND_PHONE_NUMBER;
	String FRIEND_NICKNAME;
	String FRIEND_STARTTIME, FRIEND_ENDTIME;
	String FRIEND_PREFERENCE;
	
	
	
	SharedPreferences local_user_information;
	SharedPreferences.Editor local_user_editor;
	String PREFS_NAME = "LocalUserInfo";
	
	String PHONE_NUMBER;
	String ONLINE;
	String NICKNAME;
	
	boolean IS_FRIEND_AVAILABLE_TO_ME;
	
	boolean AM_I_AVAILABLE_TO_FRIEND;
	
	Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		clientManager = new AmazonClientManager();
		
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		
		Intent intent = getIntent();
		Bundle registerInfoData = intent.getBundleExtra("friendInformation");
		FRIEND_PHONE_NUMBER = registerInfoData.getString("myFriendNumber");
		FRIEND_NICKNAME = registerInfoData.getString("myFriendName");
		
		IS_FRIEND_AVAILABLE_TO_ME = registerInfoData.getBoolean("isFriendAvailableToMe");
		
		
		
		setContentView(R.layout.friend_info_view);
		
		friendInfo_layout = (RelativeLayout) findViewById(R.id.friendInfo_layout);
		
		friendInfo_loading_layout = (RelativeLayout) findViewById(R.id.friendInfo_loading_view_layout);
		
		overridePendingTransition(R.anim.activity_left_in,R.anim.activity_left_out);
		
		if (isConnectedToInternet()){
			loadFriendInfo();
		}
		else{
			Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
		}
		
		
		
		
		
		
		
		
		
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1){
					friendInfo_loading_layout.setVisibility(View.INVISIBLE);
					friendInfo_layout.setVisibility(View.VISIBLE);
					
					
					friendNickname_textView = (TextView) findViewById(R.id.friend_nickname_textView);
					friendPhoneNumber_textView = (TextView) findViewById(R.id.friend_phone_number_display_textView);
					friendAvailability_textView = (TextView) findViewById(R.id.friend_available_time_textView);
					friendPreference_textView = (TextView) findViewById(R.id.friend_preference_textView);
					text_button = (Button) findViewById(R.id.text_button);
					call_button = (Button) findViewById(R.id.call_button);
					invisibleToThisFriend_checkBox = (CheckBox) findViewById(R.id.invisibleToThisFriend_checkBox);
					
					friendNickname_textView.setText(FRIEND_NICKNAME);
					friendPhoneNumber_textView.setText(FRIEND_PHONE_NUMBER);
					
					
					
					if (IS_FRIEND_AVAILABLE_TO_ME){
						friendPhoneNumber_textView.setTextColor(Color.BLACK);
						friendAvailability_textView.setTextColor(Color.BLACK);
						friendPreference_textView.setTextColor(Color.BLACK);
						friendAvailability_textView.setText(FRIEND_STARTTIME + " - " + FRIEND_ENDTIME);
						friendPreference_textView.setText(FRIEND_PREFERENCE);
						
						/*if (MY_BE_UNAVAILABLE_TO_LIST.containsKey(FRIEND_PHONE_NUMBER)){
							invisibleToThisFriend_checkBox.setChecked(true);
						}
						else{
							invisibleToThisFriend_checkBox.setChecked(false);
						}*/

						
						
						
					}
					else{
						friendPhoneNumber_textView.setTextColor(Color.GRAY);
						friendAvailability_textView.setTextColor(Color.GRAY);
						friendPreference_textView.setTextColor(Color.GRAY);
						friendAvailability_textView.setText("This person is currently unavailable");
						friendPreference_textView.setText("This person is currently unavailable");
						//invisibleToThisFriend_checkBox.setVisibility(View.INVISIBLE);
						//invisibleToThisFriend_checkBox.setEnabled(false);
						
						text_button.setEnabled(false);
						call_button.setEnabled(false);
						
					}
					
					/*ONLINE = local_user_information.getString("online_offline", "default");
					
					if (!ONLINE.equals("online")){
						invisibleToThisFriend_checkBox.setChecked(true);
						invisibleToThisFriend_checkBox.setEnabled(false);
					}
					*/
					if (AM_I_AVAILABLE_TO_FRIEND){
						invisibleToThisFriend_checkBox.setChecked(false);
					}
					else{
						invisibleToThisFriend_checkBox.setChecked(true);
					}
					
					
					text_button.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							textFriend();
						}
					});
					
					
					
					
					
					
					PhoneCallListener phoneListener = new PhoneCallListener();
					TelephonyManager telephonyManager = (TelephonyManager) FriendInfoActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
					telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
					
					
					
					
					
					call_button.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							callFriend();
							
							
							
						}
					});
					
					invisibleToThisFriend_checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							// TODO Auto-generated method stub
							if (isChecked){
								
								unavailableToSpecificDatabaseUpadate();
							}
							else{
								
								availableToSpecificDatabaseUpdate();
							}
							
						}
						
					});
					
					
					
					
				}
			
			

			}
		};
		
		
		
		
		
		
		
		
		
		
		
	}
	
	
	
	
	
	
	private void unavailableToSpecificDatabaseUpadate(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		ONLINE = local_user_information.getString("online_offline", "default");
		NICKNAME = local_user_information.getString("Nickname", "default");
		if (ONLINE.equals("online")){
		
			runOnUiThread(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					new Thread(new Runnable(){

						@Override
						public void run() {
							// TODO Auto-generated method stub
							
							HashMap<String, String> beUnavailableToList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);
							
							if (!beUnavailableToList.containsKey(FRIEND_PHONE_NUMBER)){

								beUnavailableToList.put(FRIEND_PHONE_NUMBER, FRIEND_NICKNAME);

								SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);
								SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM, beUnavailableToList);
							}
							
							
							HashMap<String, String> friendOnlineFriendList = SimpleDB.getAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM);
							
							if (friendOnlineFriendList.containsKey(PHONE_NUMBER)){
								HashMap<String, String> friendOfflineFriendList = SimpleDB.getAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
								
								friendOnlineFriendList.remove(PHONE_NUMBER);
								friendOfflineFriendList.put(PHONE_NUMBER, NICKNAME);
								
								SimpleDB.deleteItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM);
								SimpleDB.deleteItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
								
								SimpleDB.updateAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM, friendOnlineFriendList);
								SimpleDB.updateAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM, friendOfflineFriendList);

							}
							
							
							
							
						}

					}).start();
				}

			});
		}
	}
	
	
	
	private void availableToSpecificDatabaseUpdate(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		ONLINE = local_user_information.getString("online_offline", "default");
		NICKNAME = local_user_information.getString("Nickname", "default");
		if (ONLINE.equals("online")){
			
			runOnUiThread(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					new Thread(new Runnable(){

						@Override
						public void run() {
							// TODO Auto-generated method stub
							
							HashMap<String, String> beUnavailableToList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);
							if (beUnavailableToList.containsKey(FRIEND_PHONE_NUMBER)){
								beUnavailableToList.remove(FRIEND_PHONE_NUMBER);
								
								SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);
								SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM, beUnavailableToList);
							}
							
							
							//HashMap<String, String> friendBeUnavailableToList = SimpleDB.getAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);
				
							HashMap<String, String> friendOfflineFriendList = SimpleDB.getAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
							
							if (friendOfflineFriendList.containsKey(PHONE_NUMBER)){
								
								HashMap<String, String> friendOnlineFriendList = SimpleDB.getAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM);
								
								friendOfflineFriendList.remove(PHONE_NUMBER);
								friendOnlineFriendList.put(PHONE_NUMBER, NICKNAME);
								
								SimpleDB.deleteItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM);
								SimpleDB.deleteItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
								
								SimpleDB.updateAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM, friendOnlineFriendList);
								SimpleDB.updateAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM, friendOfflineFriendList);

								
								
							}
							
							
							
							
							
							
							
						}

					}).start();
				}

			});
		}
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	private void textFriend(){
		Log.i("Send SMS", "");

	      Intent smsIntent = new Intent(Intent.ACTION_VIEW);
	      smsIntent.setData(Uri.parse("smsto:"));
	      smsIntent.setType("vnd.android-dir/mms-sms");

	      smsIntent.putExtra("address"  , FRIEND_PHONE_NUMBER);
	      smsIntent.putExtra("sms_body"  , "");
	      try {
	         startActivity(smsIntent);
	         
	         Log.i("Finished sending SMS...", "");
	      } catch (android.content.ActivityNotFoundException ex) {
	         Toast.makeText(FriendInfoActivity.this, 
	         "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
	      }
	}
	
	
	
	
	
	
	private void callFriend(){
		
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(FriendInfoActivity.this);
		dialogBuilder.setTitle("Make a call");
		
		String message = "Are you sure you want to call " + FRIEND_NICKNAME + "("+ FRIEND_PHONE_NUMBER + ")?" ;
		dialogBuilder.setMessage(message);
		dialogBuilder.setCancelable(true);
		dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

				
				Uri number = Uri.parse("tel:" + FRIEND_PHONE_NUMBER);
				Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
				startActivity(callIntent);
			
				dialog.cancel();

			

			}
		});

		dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

				dialog.cancel();

			}
		});

		AlertDialog dialog = dialogBuilder.create();
		dialog.show();
	}
	
	
	
	private class PhoneCallListener extends PhoneStateListener {
		 
		private boolean isPhoneCalling = false;
 
		String LOG_TAG = "LOGGING 123";
 
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
 
			if (TelephonyManager.CALL_STATE_RINGING == state) {
				// phone ringing
				Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
			}
 
			if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
				// active
				Log.i(LOG_TAG, "OFFHOOK");
 
				isPhoneCalling = true;
			}
 
			if (TelephonyManager.CALL_STATE_IDLE == state) {
				// run when class initial and phone call ended, 
				// need detect flag from CALL_STATE_OFFHOOK
				Log.i(LOG_TAG, "IDLE");
 
				if (isPhoneCalling) {
 
					Log.i(LOG_TAG, "restart app");
 
					// restart app
					Intent i = getBaseContext().getPackageManager()
						.getLaunchIntentForPackage(
							getBaseContext().getPackageName());
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
 
					isPhoneCalling = false;
				}
 
			}
		}
	}
	
	
	
	
	HashMap<String, String> MY_BE_UNAVAILABLE_TO_LIST;
	
	
	private void loadFriendInfo(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						FRIEND_STARTTIME = SimpleDB.getSingleAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.AVAILABILITY_ITEM, SimpleDB.START_TIME_ATTRIBUTE);
						FRIEND_ENDTIME = SimpleDB.getSingleAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.AVAILABILITY_ITEM, SimpleDB.END_TIME_ATTRIBUTE);
						
						FRIEND_PREFERENCE = SimpleDB.getSingleAttributesForItem(clientManager, FRIEND_PHONE_NUMBER, SimpleDB.PREFERENCE_ITEM, SimpleDB.PREFERENCE_ATTRIBUTE);
						
						//MY_BE_UNAVAILABLE_TO_LIST = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);
						
						HashMap<String, String> beUnavailableToList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);
						if (beUnavailableToList.containsKey(FRIEND_PHONE_NUMBER)){
							AM_I_AVAILABLE_TO_FRIEND = false;
						}
						else{
							AM_I_AVAILABLE_TO_FRIEND = true;
						}
						
						Message msg = Message.obtain();
						msg.what = 1;
						handler.sendMessage(msg);
						
					}
					
				}).start();
			}
			
		});
	}
	
	
	private boolean isConnectedToInternet(){
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)FriendInfoActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi_network = 
				connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo mobile_network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);


		//Only for testing
		return wifi_network.isConnectedOrConnecting() || mobile_network.isConnectedOrConnecting();

		/*return mobile_network.isConnectedOrConnecting();
*/
	}
	
	
	@Override
	public void onBackPressed() {
	    super.onBackPressed();
	    overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
